package com.qingcheng.consumer;


import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.qingcheng.pojo.goods.Goods;
import com.qingcheng.pojo.goods.Sku;
import com.qingcheng.pojo.goods.Spu;
import com.qingcheng.service.goods.CategoryService;
import com.qingcheng.service.goods.SpuService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//商品详情页生成
@Service
public class PageSaveMessageConsumer implements MessageListener {

    @Value("${pagePath}")
    private String pagePath;

    @Autowired
    private TemplateEngine templateEngine;

    @Reference
    private SpuService spuService;

    @Reference
    private CategoryService categoryService;

    public void onMessage(Message message) {
        String spuId = new String(message.getBody());
        System.out.println(spuId);
        Goods goods = spuService.findGoodsById(spuId);
        //获得spu跟sku列表
        Spu spu = goods.getSpu();
        List<Sku> skuList = goods.getSkuList();

        List<String> categoryList = new ArrayList<String>();
        //获得分类列表
//        String category1 = categoryService.findById(spu.getCategory1Id()).getName();
        categoryList.add(categoryService.findById(spu.getCategory1Id()).getName());
        categoryList.add(categoryService.findById(spu.getCategory2Id()).getName());
        categoryList.add(categoryService.findById(spu.getCategory3Id()).getName());

        //sku的地址列表
        Map<String,String> urlMap= new HashMap<>();
        for (Sku sku : skuList) {
            if ("1".equals(sku.getStatus())){
                String specJson = JSON.toJSONString(JSON.parseObject(sku.getSpec()), SerializerFeature.MapSortField);
                urlMap.put(specJson,sku.getId()+".html");
            }
        }

        //为每个sku创建sku页面
        for (Sku sku : skuList) {
            Context context = new Context();
            //创建数据模型
            Map<String,Object> dataModel = new HashMap<String,Object>();
            dataModel.put("spu",spu);   //数据模型中增加spu
            dataModel.put("sku",sku);   //数据模型中添加sku
            dataModel.put("categoryList",categoryList);  //数据模型中添加分类列表
            dataModel.put("spuImages",spu.getImages().split(","));   //数据模型中添加spu图片列表
            dataModel.put("skuImages",sku.getImages().split(",")); //数据模型中添加sku图片列表
            if (spu.getParaItems()!=null || !"".equals(spu.getParaItems())){
                Map paraItems = JSON.parseObject(spu.getParaItems(),Map.class);
                dataModel.put("paraItems",paraItems);  //数据模型中添加spu参数列表
            }else{
                dataModel.put("paraItems","");
            }

            Map specItems = JSON.parseObject(sku.getSpec(),Map.class);
            dataModel.put("specItems",specItems);            //数据模型中添加当前sku的规格

            //{"颜色":["黑色"],"尺码":["30","27","25","26","28","29"]}
            Map<String,List> specMap =JSON.parseObject(spu.getSpecItems(),Map.class);
            if (specMap!=null || !specMap.isEmpty()){
                for (String key : specMap.keySet()) {
                    List<String> list = specMap.get(key);
                    List<Map> mapList = new ArrayList<Map>();
                    for (String value : list) {    //循环规格选项值
                        Map map = new HashMap();
                        map.put("option",value);
                        if(value.equals(specItems.get(key))){
//                        if(specItems.get(key).equals(value)){
                            map.put("checked",true);
                        }else {
                            map.put("checked",false);
                        }
                        Map<String,String> spec =(Map)JSON.parseObject(sku.getSpec());
                        spec.put(key,value);
                        String specJson = JSON.toJSONString(spec, SerializerFeature.MapSortField);
                        map.put("url",urlMap.get(specJson));
                        mapList.add(map);
                    }
                    specMap.put(key,mapList);   //新集合覆盖原集合
                }
            }
            dataModel.put("specMap",specMap);   //从数据模型中添加规格与规格选项

            context.setVariables(dataModel);
            //准备文件
            File dir = new File(pagePath);
            if (!dir.exists()){
                dir.mkdirs();
            }
            File dest= new File(dir,sku.getId()+".html");
            //生成页面
            try {
                PrintWriter printWriter = new PrintWriter(dest,"UTF-8");
                templateEngine.process("item",context,printWriter);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
    }
}
